<?php
/**
* 2007-12-08 yvolk simplified this class to get rid of bugs...
* @package  HTML_BBCodeParser
* @version		$Id: ContentLinks.php 0003 2007-12-08 00:00:00Z yvolk $
*/

/**
 *
 */
class HTML_BBCodeParser_Filter_Links extends HTML_BBCodeParser_Filter
{
    /**
     * An array of tags parsed by the engine
     *
     * @access   private
     * @var      array
     */
    var $_definedTags = array(
        'url' => array(
            'htmlopen'  => 'a target=\'_blank\'',
            'htmlclose' => 'a',
            'allowed'   => 'none^img',
            'attributes'=> array('url' => 'href=%2$s%1$s%2$s')
        )
    );

    /**
     * Executes statements before the actual array building starts
     *
     * This method should be overwritten in a filter if you want to do
     * something before the parsing process starts. This can be useful to
     * allow certain short alternative tags which then can be converted into
     * proper tags with preg_replace() calls.
     * The main class walks through all the filters and and calls this
     * method if it exists. The filters should modify their private $_text
     * variable.
     *
     * @return   none
     * @access   private
     * @see      $_text
     * @author   Stijn de Reede <sjr@gmx.co.uk>
     * @author   Seth Price <seth@pricepages.org>
     */
    function _preparse()
    {
        $options = PEAR::getStaticProperty('HTML_BBCodeParser', '_options');
        $oe = $options['open_esc'];
        $ce = $options['close_esc'];

  			$pattern = array(
          '!'.$oe.'((url=([^\[\]]*))|(url))'.$ce.'([^\[\]]*)'.$oe.'/url'.$ce.'!i'
        );  

        $pp = $this->_text;
        $this->_preparsed = preg_replace_callback($pattern[0], array($this, 'parseUrl'), $pp);
    }

    function parseUrl($matches)
    {
      $debug = false;
      $ret = '';

      $options = PEAR::getStaticProperty('HTML_BBCodeParser','_options');
      $o = $options['open'];
      $c = $options['close'];

			$url = '';
      $text = $matches[5];

			if ($matches[3]) {
				$url = $matches[3];
			} elseif ($matches[4]) {
			  // [url]	
				$url = $text;
			}

      if ($debug) {
        $ret .= '<br>start';
        $ret .= '; url="' .  $url . '" ';
        $ret .= '; matchers="' . preg_replace('([\[\]]+)', '*', print_r($matches, true)) . '" ';
        $ret .= '<br>replaced with: ';
      }  

      if ($url == '') {
      	$ret .= $text;
      } else {
        $ret .= $o . 'url=' . $url . $c . $text . $o . '/url' . $c;
      }
      if ($debug) {
        $ret .= '<br>end<br>';
      }  
      return $ret;
        
    }
}
?>